<?php
namespace app\admin\controller;
use app\admin\model\CourseArticle;
class Course extends Basic
{
    private $model;
    private $Praise;
    private $CourseArticle;
    public $types = [
        1=>'所有人免费',
        2=>'会员免费订阅、非会员可免费试听2期也可单独购买该小课包',
        3=>'仅供会员免费订阅、非会员可试听2期但不可以购买单独小课包',
        4=>'会员免费，非会员免费阅读第一篇的1/3',
    ];
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model= new \app\admin\model\Course();
        $this->Praise= new \app\admin\model\Praise();
        $this->CourseArticle= new \app\admin\model\CourseArticle();
    }

    /**
     * 小课列表
     */
    public function index()
    {
        $key= input('key','');
        $page = input('page',1);
        $ctype = input('type','');
        $type = input('fftype','');
        $limit = input('limit',10);
        $map['status'] = array('neq',0);
        if($ctype) {
            $map['ctype'] = $ctype;
        }
        if($type) {
            $map['type'] = $type;
        }
            
         if (!empty($key)){
             $one['title|author']=['like','%'.$key.'%'];
             $dataList['list']=$this->model->where($map)->where($one)->page($page,$limit)->order('sort desc,create_time desc')->select();
             $dataList['count']=$this->model->where($map)->where($one)->count();
         }else{
             $dataList['list']=$this->model->where($map)->page($page,$limit)->order('sort desc,create_time desc')->select();
             $dataList['count']=$this->model->where($map)->count();
         }
        $dataList['praise_arr'] = [];
        foreach ($dataList['list'] as $k=> $v){

            $v['price']=$v['price']/100;
            // 小课点赞数
            $praise_num = 0;
            $articles=$this->CourseArticle->where('course_id',$v['id'])->where('status',1)->order('sort')->find();
            if($articles) {
                foreach ($articles as $a) {
                    $praise_num += $this->Praise->where('type',1)->where('oid',$a['id'])->count();
                }
            }
            $dataList['list'][$k]['is_video'] = $dataList['list'][$k]['ctype']==1?'音频小课':($dataList['list'][$k]['ctype']==2?'视频小课':'专栏小课');
            $dataList['list'][$k]['type'] = isset($this->types[$dataList['list'][$k]['type']])?$this->types[$dataList['list'][$k]['type']]:'暂无';
            $dataList['praise_arr'][] = $praise_num;
        }

         json_success($dataList);
    }

    public function typelist()
    {
        json_success([['id'=>1,'name'=>'所有人免费'],['id'=>2,'name'=>'会员免费订阅、非会员可免费试听2期也可单独购买该小课包'],['id'=>3,'name'=>'仅供会员免费订阅、非会员可试听2期但不可以购买单独小课包'],['id'=>4,'name'=>'会员免费，非会员免费阅读第一篇的1/3']]);
    }


    /**
     * 新增小课
     */
    public function create()
    {
        if (!$this->request->isPost()){
            json_success('请求类型错误');
        }
        $request=input('post.');
        $request['price']=$request['price']*100;
        $res=$this->model->allowField(true)->isUpdate(false)->save($request);
        if (!empty($res)){
            json_success('添加成功');
        }
        json_success('添加失败');
    }


    /**
     * 显示要修改的小课
     * @param $id
     */
    public function edit($id)
    {
        if(empty($id)){
            json_fail('参数ID错误');
        }
        $data=$this->model->where('id',$id)->find();
        $data['price']=$data['price']/100;
        if (!empty($data)){
            json_success($data);
        }
        json_success('无');
    }
    /**
     * 修改小课
     */
    public function update()
    {
        if (!$this->request->isPost()){
            json_success('请求类型错误');
        }
        $request=input('post.');
         $request['price']=$request['price']*100;


//        $res=$this->model->where('id',$request['id'])->update($request);
        $obj=\app\admin\model\Course::get($request['id']);
        $res=$obj->allowField(true)->isUpdate(true)->save($request);

        if (!empty($res)){
            json_success('修改成功');
        }
        json_success('未修改内容');
    }

    /**
     * 删除小课
     * @param $id
     */
    public function delete($id)
    {
        if (empty($id)) {
            json_fail('缺少参数ID');
        }
        $data = $this->model->where('id', $id)->find();
        if (!empty($data)) {
            $CourseArticle=new CourseArticle();
            $data=$CourseArticle->where('course_id',$id)->where('status','neq',0)->count();
            if (!empty($data)){
            json_fail('小课下有内容不能删除');
            }
            $update=['status'=>0];
            $res=$this->model->where('id',$id)->update($update);
            if (!empty($res)){
                json_success('删除成功');
            }
            json_fail('删除失败');
        }
        json_success('无数据');
    }

    // 创建二维码
    public function create_qr()
    {
        $db = input('db','');
        $id = input('id','');
        $path = input('path','');
        $obj = Db($db)->where(['id'=>$id])->find();
         //实例化数据库
            $token = token();

            //获取二维码
            //$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$token;
            $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$token;
            //跳转页面
            $data = array(
                'path' => $path,
            );
            $code = json_encode($data);
            $imgInfo = $this->api_notice_increment($url, $code);
            $local = 'static/Code/' . date('YmdHis') . rand(1221212, 1212012102102) . '.png';
            file_put_contents($local, $imgInfo);
            $code_url = $this->upImg($local);
            $url =  input('server.REQUEST_SCHEME') . '://' .$_SERVER['HTTP_HOST'].'/'.$local;
            Db($db)->where(['id'=>$id])->update(['qr'=>$url]);
            // return config('server_url').'/'.$local;
        // if(!$obj['qr']) {
           
        // }

    }


}
